﻿using AutoMapper;
using CK.Sprite.Framework;
using JetBrains.Annotations;
using Newtonsoft.Json;
using System;
using System.Data;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace CK.Sprite.Form.Core
{
    public class SpriteObjectHandler : AbstractSpriteObjectHandler, ITransientDependency
    {
        protected override async Task DoAddSpriteObjectAsync(SpriteObjectDto spriteObjectDto)
        {
            SpriteObject spriteObject = MapToSpriteObject(spriteObjectDto);

            GuidRepositoryBase<SpriteObject> spriteObjectRepository = new GuidRepositoryBase<SpriteObject>(DesignUnitOfWork);
            await spriteObjectRepository.InsertAsync(spriteObject);
        }

        public async Task ChangeObjectProperty(Guid objectId, ISpriteObjectRepository spriteObjectRepositoryParam = null)
        {
            var spriteObjectRepository = spriteObjectRepositoryParam == null ? ConnectionFactory.GetConnectionProvider(DefaultDbConfig.ConnectionType).GetRepository<ISpriteObjectRepository>(DesignUnitOfWork) : spriteObjectRepositoryParam;
            await spriteObjectRepository.ChangeObjectProperty(objectId);
        }

        public async Task<SpriteObject> GetSpriteObject(Guid objectId)
        {
            GuidRepositoryBase<SpriteObject> spriteObjectRepository = new GuidRepositoryBase<SpriteObject>(DesignUnitOfWork);
            return await spriteObjectRepository.GetAsync(objectId);
        }

        #region Mapper

        private SpriteObject MapToSpriteObject(SpriteObjectDto spriteObjectDto)
        {
            SpriteObject spriteObject = Mapper.Map<SpriteObject>(spriteObjectDto);

            var serializeService = _serviceProvider.GetService<ISerializeService>();
            spriteObject.PropertyJsons = serializeService.SerializeObject(spriteObjectDto.ObjectPropertyDtos);

            return spriteObject;
        }

        #endregion
    }
}
